<template>
  <view class="order-view">
    <!-- 日期选择部分 -->
    <!-- <view class="block">
      <span class="demonstration">选择日期 :</span>
      <picker mode="date" :value="date" @change="dateChange">
        <view class="date-picker">{{ formattedDate }}</view>
      </picker>
    </view>
    <view class="order">
      <view class="title">{{ title }}</view>
    </view>
    <view class="select-container">
      <view class="select">
        <view class="select-btn" v-for="(item, index) in combinedList" :key="index">
          <view @click="selectProject(item.gym_name)" class="image-container">
            <image class="img1" :src="item.img1" mode="aspectFit" />
            <image class="img2" :src="item.img2" mode="aspectFit" />
          </view> -->
    <!-- 时间选择区域 -->
    <!--  <view class="select-sx">
            <view v-for="(timeItem, timeIndex) in item.TimeList" :key="timeIndex" class="select-time-item"
              :class="timeItemClass(item.gym_id, timeItem.id)" @click="selects(item.gym_id, timeItem.id, $event)">
              <span style="color: #fff; line-height: 25px">{{ timeItem.text }}</span>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 预约按钮 -->
    <!-- <view class="booking" @click="setLocal(Selects, gym_id, combinedList)">
      <span class="date">预约</span>
    </view> -->
  </view>
</template>

<script>
  export default {
    data() {
      return {
        title: '体育中心',
        date: new Date().toISOString().slice(0, 10),
        formattedDate: this.formatDate(new Date()),
        Selects: [],
        selectedTimes: [], // Track selected time slots
        gym_id: "",
        targetData: {},
        targetData: null,
        combinedList: [{
            idClass: 1,
            img1: '../../static/images/football.png',
            img2: '../../static/images/football1.png',
            gym_name: '足球',
            gym_id: '1',
            TimeList: [{
                id: 1,
                text: '08:00 - 09:00'
              },
              {
                id: 2,
                text: '09:00 - 10:00'
              },
              {
                id: 3,
                text: '10:00 - 11:00'
              },
              {
                id: 4,
                text: '11:00 - 12:00'
              },
              {
                id: 5,
                text: '12:00 - 13:00'
              },
              {
                id: 6,
                text: '13:00 - 14:00'
              },
              {
                id: 7,
                text: '14:00 - 15:00'
              },
              {
                id: 8,
                text: '15:00 - 16:00'
              },
              {
                id: 9,
                text: '16:00 - 17:00'
              }
            ]
          },
          {
            idClass: 2,
            img1: '../../static/images/football.png',
            img2: '../../static/images/football1.png',
            gym_name: '足球',
            gym_id: '2',
            TimeList: [{
                id: 1,
                text: '08:00 - 09:00'
              },
              {
                id: 2,
                text: '09:00 - 10:00'
              },
              {
                id: 3,
                text: '10:00 - 11:00'
              },
              {
                id: 4,
                text: '11:00 - 12:00'
              },
              {
                id: 5,
                text: '12:00 - 13:00'
              },
              {
                id: 6,
                text: '13:00 - 14:00'
              },
              {
                id: 7,
                text: '14:00 - 15:00'
              },
              {
                id: 8,
                text: '15:00 - 16:00'
              },
              {
                id: 9,
                text: '16:00 - 17:00'
              }
            ]
          },
          {
            idClass: 3,
            img1: '../../static/images/football.png',
            img2: '../../static/images/football1.png',
            gym_name: '足球',
            gym_id: '3',
            TimeList: [{
                id: 1,
                text: '08:00 - 09:00'
              },
              {
                id: 2,
                text: '09:00 - 10:00'
              },
              {
                id: 3,
                text: '10:00 - 11:00'
              },
              {
                id: 4,
                text: '11:00 - 12:00'
              },
              {
                id: 5,
                text: '12:00 - 13:00'
              },
              {
                id: 6,
                text: '13:00 - 14:00'
              },
              {
                id: 7,
                text: '14:00 - 15:00'
              },
              {
                id: 8,
                text: '15:00 - 16:00'
              },
              {
                id: 9,
                text: '16:00 - 17:00'
              }
            ]
          }
        ],
        project: [],
        Class: [], // 用于存储超时信息
        blueList: [] // 已预约的时间段
      }
    },
    computed: {
      timeItemClass() {
        return (gym_id, timeId) => {
          // 找到对应的时间文本
          let timeText = '';
          const targetItem = this.combinedList.find(item => item.gym_id === gym_id);
          if (targetItem) {
            const timeItem = targetItem.TimeList.find(item => item.id === timeId);
            if (timeItem) {
              timeText = timeItem.text;
            }
          }

          // 检查当前时间是否超时
          const currentTime = new Date().getTime();
          // 转换日期格式以兼容iOS系统
          const formattedDate = this.date.replace(/-/g, '/');
          const time = new Date(`${formattedDate} ${timeText.split(' - ')[0]}`).getTime();
          const isTimeout = currentTime > time;

          // 检查当前时间是否已被预约
          const isBooked = this.blueList.includes(timeId);

          // 检查是否被选中
          const isSelected = this.selectedTimes.some(t => t.gym_id === gym_id && t.id === timeId);

          return {
            grey: isTimeout,
            ordered: isBooked,
            blue: isSelected,
            green: !isTimeout && !isBooked && !isSelected
          };
        };
      }
    },
    methods: {
      // 格式化日期
      formatDate(date) {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}/${month}/${day}`
      },

      // 日期选择
      dateChange(event) {
        this.date = event.detail.value;
        // console.log('Selected date:', event);
        this.formattedDate = this.formatDate(new Date(this.date));

        // Clear selected times when date changes
        this.selectedTimes = [];
        this.Selects = [];

        // Show message if trying to select greyed out slots
        this.$nextTick(() => {
          const greySlots = document.querySelectorAll('.grey');
          greySlots.forEach(slot => {
            slot.addEventListener('click', () => {
              uni.showToast({
                title: '该时间段已超时，不可选择',
                icon: 'none'
              });
            });
          });
        });
      },
      selectProject(gymName) {
        console.log('Selected:', gymName);
      },
      // 选择时间段
      selects(gym_id, id, event) {

        if (event && event.currentTarget) {
          const element = event.currentTarget;
          if (element.classList) {
            element.classList.add('click-animate');
            setTimeout(() => {
              element.classList.remove('click-animate');
            }, 100);
          }
        }

        // Check if time is already selected
        const index = this.selectedTimes.findIndex(t => t.gym_id === gym_id && t.id === id);
        this.gym_id = gym_id;
        if (index >= 0) {
          // Deselect if already selected
          this.selectedTimes.splice(index, 1);
        } else {
          // Check if we've reached max selection (4)
          if (this.selectedTimes.length >= 4) {
            uni.showToast({
              title: '最多选择4个时间段',
              icon: 'none'
            });
            return;
          }

          // Add new selection
          this.selectedTimes.push({
            gym_id,
            id
          });
        }

        // Update Selects array for reservation
        this.Selects = this.selectedTimes;

      },
      // 预约
      setLocal(Selects, gym_id, combinedList) {
        // 获取选中的时间段信息
        const selectedProject = combinedList.find(item => item.gym_id === gym_id);
        // 获取所有选中的时间段
        const selectedTimeSlots = selectedProject?.TimeList.filter(slot =>
          Selects.some(s => s.gym_id === gym_id && s.id === slot.id)
        );

        // 检查是否选择了场地和时间
        if (!selectedProject || !selectedTimeSlots?.length) {
          uni.showToast({
            title: '未找到选中的场地或时间段',
            icon: 'none'
          });
          return;
        }

        // 将选中的时间段转换为URL参数
        const timeSlotsParam = selectedTimeSlots.map(slot =>
          `${slot.id}|${slot.text}` // 修改为同时包含id和text，用|分隔
        ).join(',');

        // 跳转到订单详情页并携带参数
        uni.navigateTo({
          url: `/reservation/DetailView/DetailView?gymId=${selectedProject.gym_id}&gymName=${selectedProject.gym_name}&address=${selectedProject.address}&description=${selectedProject.description}&timeSlots=${timeSlotsParam}&date=${this.formattedDate}`
        });
      }


    },
    onLoad(options) {

      // 获取从HomeView传递的index参数
      const {
        index
      } = options;

      const data = uni.getStorageSync('data') || [];
      // 根据index定位到需要的数组项
      this.targetData = data[index];
      // 假设projects数组已通过某种方式获取，这里模拟获取数据
      this.projects = this.targetData.projects;
      // 处理projects数据生成combinedList
      this.combinedList = this.projects.map(project => ({
        address: this.targetData.address,
        description: this.targetData.description,
        idClass: this.targetData.id,
        // img1: this.targetData?.img1 || '',
        // img2: this.targetData?.img2 || '',
        gym_name: this.targetData.name,
        gym_id: project.id.toString(),
        TimeList: project.timeSlots.map(slot => ({
          id: slot.id,
          text: `${slot.startTime.slice(0, 5)} - ${slot.endTime.slice(0, 5)}`
        }))
      }));
      // 打印到控制台
      // console.log(this.combinedList);
    },
  }
</script>

<style scoped>
  .title {
    color: #fff;
  }

  .order-view {
    background-color: #159B38;
    text-align: center;
    /* padding: 20px; */
    color: #fff;
    position: relative;
    min-height: 100vh;
  }

  .select-container {
    text-align: center;
    padding: 20px;
    display: flex;
    justify-content: center;
  }

  .select {
    display: flex;
    width: 300px;
    /* flex-wrap: wrap; */
    flex-direction: column;
    /* align-items: center; */
    justify-content: center;
    gap: 1px;
    /* background-color: blue; */
  }

  .select-btn {
    position: relative;
    display: inline-block;
    width: 300px;
    height: 250px;
    display: flex;
    flex-direction: column;
    align-items: center;

  }

  .img1 {
    width: 300px;
    height: 200px;
    position: relative;
    /* z-index: 1; */

  }

  .img2 {
    width: 100px;
    height: 100px;
    position: absolute;
    top: 55px;
    left: 100px;
    z-index: 2;
  }

  /* 时间选择样式 */
  .select-sx {
    width: 270px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-top: 3px;
    transform: translateY(-115%);
  }

  .select-time-item {
    display: inline-block;
    border-radius: 10px;
    width: 100px;
    height: 25px;
    margin: 4px 0px;
    cursor: pointer;
    transition: 0.2s;
    box-shadow: 1px 1px 5px 0px rgba(50, 50, 50, 0.75);
    transform: scale(1);
    text-align: center;
    font-size: 12px;
  }

  .grey {
    background-color: grey;
  }

  .green {
    background-color: #31ad52;
  }

  .ordered {
    background-color: rgb(236, 151, 24);
  }

  .blue {
    background-color: #1E90FF;
  }

  .click-animate {
    transform: scale(0.95);
    transition: transform 0.1s ease;
  }

  /* 预约按钮 */
  .booking {
    background-color: #159b38;
    color: #fff;
    padding: 10px 10px;
    border-radius: 8px;
    position: fixed;
    right: 0px;
    width: 14px;
    top: 30%;
    cursor: pointer;
    transition: 0.2s;
    box-shadow: 1px 1px 5px 0px rgba(50, 50, 50, 0.75);
  }

  /* 日期选择样式 */
  .block {
    display: flex;
    justify-content: flex-end;
    font-size: 18px;
    align-items: center;
    padding: 10px 20px;
    height: 5vh;
  }

  .left {
    width: 15px;
    height: 20px;
    position: absolute;
    left: 12px;
    top: 15px;

  }

  .demonstration {
    color: #fff;
    font-size: 14px;
    margin-right: 10px;
  }

  .date-picker {
    display: inline-block;
    color: #fff;
    width: 110px;
    padding: 0px 0;
    height: 3vh;
    background-color: #159b38;
    border-radius: 5px;
  }
</style>